import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] array = {12,8,5,4,10,15};
        creationHeap(array);// 建堆的时间复杂度：O(N)
        System.out.println(Arrays.toString(array));
        heapSort(array);// 堆排序的时间复杂度：O(N * log2 N)
        // 空间复杂度：O(1)
        System.out.println(Arrays.toString(array));
    }
    // 创建一个大根堆
    public static void creationHeap(int[] array){
        for (int parent = (array.length-1-1)/2; parent >= 0; parent--) {
            shiftDown(array,parent,array.length);
        }
    }
    public static void heapSort(int[] array){
        /*
        * 时间复杂度：O(N * log2 N)
        * 空间复杂度：O(1)
        * 稳定性：不稳定
        * */
        int end = array.length - 1;
        while(end>0){
            int tmp = array[end];
            array[end] = array[0];
            array[0] = tmp;
            shiftDown(array,0,end);
            end--;
        }
    }
    // 向下调整
    public static void shiftDown(int[] array,int parent,int len){
        int child = parent * 2 + 1;// 做孩纸
        while(child < len){
            // 获取左右子树最大值的下标
            if(child+1 < len && (array[child] < array[child+1])){
                child++;
            }
            if(array[child] > array[parent]){
                int tmp = array[child];
                array[child] = array[parent];
                array[parent] = tmp;
                parent = child;
                child = parent * 2 + 1;
            }else{
                break;
            }
        }
    }
}
